"""
配置模块 - 正则表达式模式配置
支持流水线式扩展，便于添加新的清理规则和识别模式

作者: Claude
创建时间: 2024-09-14
"""

from typing import List, Dict, Any
from dataclasses import dataclass


@dataclass
class CleaningPattern:
    """清理模式配置"""
    name: str                    # 模式名称
    pattern: str                 # 正则表达式
    description: str            # 描述信息
    priority: int = 0           # 优先级，数字越大越优先


@dataclass  
class ExtractionPattern:
    """提取模式配置"""
    name: str                   # 模式名称
    pattern: str                # 正则表达式
    description: str            # 描述信息
    group_index: int = 1       # 提取组索引
    priority: int = 0          # 优先级


class PatternConfig:
    """模式配置管理器 - 支持流水线扩展"""
    
    def __init__(self):
        """初始化配置"""
        self._cleaning_patterns = self._init_cleaning_patterns()
        self._fc2_patterns = self._init_fc2_patterns()
        self._censored_patterns = self._init_censored_patterns()
        self._uncensored_patterns = self._init_uncensored_patterns()
        self._special_transforms = self._init_special_transforms()
    
    def _init_cleaning_patterns(self) -> List[CleaningPattern]:
        """初始化清理模式 - 流水线式配置，可随时添加新规则"""
        return [
            # 第一阶段：清理网站前缀
            CleaningPattern(
                name="website_url_general",
                pattern=r'[a-zA-Z0-9.-]*\.(?:com|net|org|cn|la|me|co|tv|biz|info)[@_]?',
                description="通用网址删除",
                priority=11
            ),
            
            # 第二阶段：清理方括号标记
            CleaningPattern(
                name="bracket_thz",
                pattern=r'\[Thz\.la\]',
                description="清理Thz.la标记",
                priority=9
            ),
            CleaningPattern(
                name="bracket_456k",
                pattern=r'\[456k\.me\]',
                description="清理456k.me标记", 
                priority=9
            ),
            CleaningPattern(
                name="bracket_psk",
                pattern=r'\[psk\.la\]',
                description="清理psk.la标记",
                priority=9
            ),
            # 通用方括号清理（包括空的方括号）
            CleaningPattern(
                name="empty_brackets",
                pattern=r'\[\]',
                description="清理空方括号",
                priority=8
            ),
            CleaningPattern(
                name="general_brackets",
                pattern=r'\[[^\]]*\]',
                description="通用方括号清理",
                priority=7
            ),
            
            # 第三阶段：清理质量标记
            CleaningPattern(
                name="quality_fhd_dot",
                pattern=r'\.FHD',
                description="清理.FHD质量标记",
                priority=8
            ),
            CleaningPattern(
                name="quality_fhd_underscore", 
                pattern=r'_FHD',
                description="清理_FHD质量标记",
                priority=8
            ),
            
            # 第四阶段：清理中文描述和标记
            CleaningPattern(
                name="chinese_description",
                pattern=r'【[^】]*】',
                description="清理中文方括号描述",
                priority=7
            ),
            CleaningPattern(
                name="chinese_at_markers",
                pattern=r'@[^@]*@',
                description="清理@中文标记@",
                priority=7
            ),
            CleaningPattern(
                name="carib_suffix",
                pattern=r'-carib-\w+',
                description="清理carib后缀",
                priority=6
            ),
            
            # 第五阶段：清理1pon相关内容
            CleaningPattern(
                name="1pon_whole_hd",
                pattern=r'-1pon-whole\d+_hd',
                description="清理1pon完整版标记",
                priority=6
            ),
            CleaningPattern(
                name="whole_hd",
                pattern=r'-whole\d+_hd',
                description="清理whole_hd标记",
                priority=6
            ),
            CleaningPattern(
                name="trailing_hd",
                pattern=r'_hd$',
                description="清理末尾_hd标记",
                priority=6
            ),
            
            # 第六阶段：特殊变换规则
            CleaningPattern(
                name="4k60fps_transform",
                pattern=r'_4K60fps',
                description="4K60fps转换为-4K",
                priority=5
            ),
        ]
    
    def _init_fc2_patterns(self) -> List[ExtractionPattern]:
        """初始化FC2识别模式"""
        return [
            ExtractionPattern(
                name="fc2_ppv_standard",
                pattern=r'FC2[-_]?PPV[-_]?(\d+)',
                description="标准FC2-PPV格式",
                priority=10
            ),
            ExtractionPattern(
                name="fc2_ppv_compact",
                pattern=r'FC2PPV[-_]?(\d+)',
                description="紧凑FC2PPV格式",
                priority=9
            ),
            ExtractionPattern(
                name="fc2_standard",
                pattern=r'FC2[-_]?(\d+)',
                description="标准FC2格式",
                priority=8
            ),
            ExtractionPattern(
                name="fc_prefix",
                pattern=r'fc(\d+)',
                description="fc前缀格式",
                priority=7
            ),
            ExtractionPattern(
                name="ppv_only",
                pattern=r'PPV[-_]?(\d+)',
                description="仅PPV格式",
                priority=6
            ),
            ExtractionPattern(
                name="fc_number_only",
                pattern=r'^FC(\d{7,})',
                description="FC+数字格式（无分隔符）",
                priority=6
            ),
            ExtractionPattern(
                name="pure_number_with_cd",
                pattern=r'^(\d{7,})[-_]?(?:CD)?(\d+)?',
                description="纯数字格式（可能带CD分段）",
                priority=5
            ),
            ExtractionPattern(
                name="pure_number",
                pattern=r'^(\d{7,})(?:\.|\s|$|\-)',
                description="纯数字格式",
                priority=4
            ),
        ]
    
    def _init_censored_patterns(self) -> List[ExtractionPattern]:
        """初始化有码识别模式"""
        return [
            # 特殊系列优先识别
            ExtractionPattern(
                name="ssis_series",
                pattern=r'(SSIS\d+)',
                description="SSIS系列",
                priority=10
            ),
            ExtractionPattern(
                name="skyhd_series", 
                pattern=r'(SKYHD[-_]?\d+)',
                description="SKYHD系列",
                priority=10
            ),
            ExtractionPattern(
                name="siro_series",
                pattern=r'(SIRO[-_]?\d+)', 
                description="SIRO系列",
                priority=10
            ),
            ExtractionPattern(
                name="sone_series",
                pattern=r'(SONE[-_]?\d+)',
                description="SONE系列",
                priority=10
            ),
            
            # 通用系列模式
            ExtractionPattern(
                name="waaa_series",
                pattern=r'(WAAA[-_]?\d+)',
                description="WAAA系列",
                priority=9
            ),
            ExtractionPattern(
                name="vrtm_series",
                pattern=r'(VRTM[-_]?\d+)',
                description="VRTM系列", 
                priority=9
            ),
            ExtractionPattern(
                name="start_series",
                pattern=r'(START[-_]?\d+)',
                description="START系列",
                priority=9
            ),
            ExtractionPattern(
                name="vec_series",
                pattern=r'(VEC[-_]?\d+)',
                description="VEC系列",
                priority=9
            ),
            ExtractionPattern(
                name="ure_series",
                pattern=r'(URE[-_]?\d+)',
                description="URE系列",
                priority=9
            ),
            ExtractionPattern(
                name="ssni_series",
                pattern=r'(SSNI[-_]?\d+)',
                description="SSNI系列",
                priority=9
            ),
            ExtractionPattern(
                name="val_series",
                pattern=r'(VAL[-_]?\d+)',
                description="VAL系列",
                priority=9
            ),
            ExtractionPattern(
                name="xv_series",
                pattern=r'(XV[-_]?\d+)',
                description="XV系列",
                priority=9
            ),
            ExtractionPattern(
                name="fsdss_series",
                pattern=r'(FSDSS[-_]?\d+)',
                description="FSDSS系列",
                priority=9
            ),
            ExtractionPattern(
                name="hmn_series",
                pattern=r'(HMN[-_]?\d+)', 
                description="HMN系列",
                priority=9
            ),
            ExtractionPattern(
                name="atid_series",
                pattern=r'(ATID[-_]?\d+)',
                description="ATID系列",
                priority=9
            ),
            
            # 通用格式
            ExtractionPattern(
                name="generic_3_4_letters",
                pattern=r'([A-Z]{3,4}[-_]?\d{3,})',
                description="通用3-4字母系列",
                priority=5
            ),
            ExtractionPattern(
                name="generic_2_letters",
                pattern=r'([A-Z]{2}[-_]?\d{3,})',
                description="通用2字母系列", 
                priority=4
            ),
        ]
    
    def _init_uncensored_patterns(self) -> List[ExtractionPattern]:
        """初始化无码识别模式"""
        return [
            # 特殊无码系列（高优先级）
            ExtractionPattern(
                name="heyzo_series",
                pattern=r'(HEYZO)[-_]?(?:HD[-_]?)?(\d+)',
                description="HEYZO系列",
                priority=15
            ),
            ExtractionPattern(
                name="caribbeancom_series",
                pattern=r'(CARIBBEANCOM)[-_]?(\d+)',
                description="CARIBBEANCOM系列",
                priority=14
            ),
            ExtractionPattern(
                name="1pon_series",
                pattern=r'(1PON)[-_]?(\d+)',
                description="1PON系列",
                priority=13
            ),
            ExtractionPattern(
                name="10musume_series",
                pattern=r'(10MUSUME)[-_]?(\d+)',
                description="10MUSUME系列",
                priority=12
            ),
            # 标准数字格式
            ExtractionPattern(
                name="number_underscore_number",
                pattern=r'(\d+_\d+)',
                description="数字_数字格式（下划线）",
                priority=10
            ),
            ExtractionPattern(
                name="number_dash_number", 
                pattern=r'(\d+[-]\d+)',
                description="数字-数字格式（横线）",
                priority=9
            ),
        ]
    
    def _init_special_transforms(self) -> Dict[str, Any]:
        """初始化特殊变换规则"""
        return {
            # 4K标记变换
            "4k_transforms": [
                (r'_4K60fps', '-4K'),
                (r'4K60fps', '-4K'),
                (r'\.4K', '-4K'),
                (r'_4K', '-4K'),
            ],
            
            # CD分段变换
            "cd_transforms": [
                (r'part(\d+)', r'-CD\1'),
                (r'Part(\d+)', r'-CD\1'),
                (r'PART(\d+)', r'-CD\1'),
                (r'_(\d+)$', r'-CD\1'),  # 以下划线+数字结尾的转为CD
                (r'-(\d+)$', r'-CD\1'),  # 以横线+数字结尾的转为CD
            ],
            
            # 字幕标记标准化
            "subtitle_markers": ['-c', '-C', '_c', '_C'],
        }
    
    # 公共接口方法
    def get_cleaning_patterns(self) -> List[CleaningPattern]:
        """获取清理模式列表（按优先级排序）"""
        return sorted(self._cleaning_patterns, key=lambda x: x.priority, reverse=True)
    
    def get_fc2_patterns(self) -> List[ExtractionPattern]:
        """获取FC2识别模式列表"""
        return sorted(self._fc2_patterns, key=lambda x: x.priority, reverse=True)
    
    def get_censored_patterns(self) -> List[ExtractionPattern]:
        """获取有码识别模式列表"""
        return sorted(self._censored_patterns, key=lambda x: x.priority, reverse=True)
    
    def get_uncensored_patterns(self) -> List[ExtractionPattern]:
        """获取无码识别模式列表"""
        return sorted(self._uncensored_patterns, key=lambda x: x.priority, reverse=True)
    
    def get_special_transforms(self) -> Dict[str, Any]:
        """获取特殊变换规则"""
        return self._special_transforms.copy()
    
    def add_cleaning_pattern(self, pattern: CleaningPattern) -> None:
        """添加新的清理模式"""
        self._cleaning_patterns.append(pattern)
    
    def add_extraction_pattern(self, video_type: str, pattern: ExtractionPattern) -> None:
        """添加新的提取模式"""
        if video_type.upper() == "FC2":
            self._fc2_patterns.append(pattern)
        elif video_type.upper() == "CENSORED":
            self._censored_patterns.append(pattern)
        elif video_type.upper() == "UNCENSORED":
            self._uncensored_patterns.append(pattern)
        else:
            raise ValueError(f"不支持的视频类型: {video_type}")


# 全局配置实例
pattern_config = PatternConfig()